<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" session="false" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!doctype HTML>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
        <title> 车友会 —— 留言板 </title>
        <meta name="keywords" content="" />
        <meta name="description" content="" />
        <meta name="author" content="lijun_gz none" />
        <link rel="stylesheet" type="text/css" href="http://js.3conline.com/wap/pcauto/2014/touch/cyh.css">
    </head>

    <body class="g-doc" style="background: #f5f5f5" id="J-main">
        <!--栏目计数器/文章计数器-->
        <script>document.body.insertBefore(document.createElement("script"),document.body.firstChild).src="http://count.pcauto.com.cn/count.php?channel=7389&screen="+screen.width+"*"+screen.height+"&refer="+encodeURIComponent(document.referrer)+"&anticache="+new Date().getTime()+"&url="+encodeURIComponent(location.href);</script>
        <%@include file="../common/intf6007.html" %>
        <!-- 公共头部 -->
        <div class="g-hd">
            <a href="http://m.pcauto.com.cn" class="header-home" title="太平洋汽车网"></a>
            <div class="header-title">
                <span class="header-title-nav">
                    <a href="${WAPROOT}/">车友会</a>&nbsp;&gt;&nbsp;<a href="${WAPROOT}/${myUrl}/"> ${fn:length(fn:escapeXml(club.name))>8?fn:substring(fn:escapeXml(club.name),0,8):fn:escapeXml(club.name)}${fn:length(fn:escapeXml(club.name))>8?"...":""}</a>  > 留言板
                </span>
            </div>
        </div>

        <div class="m-lylist">
          
            <div class="comment" id="comment">
			<c:if test="${user==null || user.uid==0}">
	            <div class="firstLogin" id="noLogin" >
	                <p class="th">请您先登录后发表留言</p>
	                <div class="btnWrap" id="aeaoofnhgocdbnbeljkmbjdmhbcokfdb-mousedown">
	                        <a href="javascript:window.location.href = '${UCROOT}/my/passport/login.jsp?return=' + window.location.href">登录</a>
	                        <a href="javascript:window.location.href = '${UCROOT}/my/passport/register.jsp?return=' + window.location.href">注册</a>
	                </div>
	            </div>
            </c:if>
			<!-- 评论输入 -->
			<c:if test="${user!=null && user.uid!=0}">
				<c:choose>
					<c:when test="${isMember}">
						<div class="c-input">
		                    <div class="c-top">
		                        <div class="c-face"><span class="c-face-btn">表情</span><span class="c-face-list"></span></div>
		                        <div class="picfileWrap" id="picfileWrap">
		                            <input type="file" name="picfile0" id="picfile0" class="picfile" onchange="changeEvent(this)" accept="image/*"><em>&nbsp图片</em>
		                        </div>
		                        <div class="picWrap" id="picWrap"></div>
		                    </div>
		                    <div class="c-area">
		                        <textarea id="content" rows="" cols="" placeholder="在这里输入留言"></textarea>
		                    </div>
		                    <div class="c-check" id="cmtCheck">
		                        <input type="text" id="captcha" placeholder="验证码"><a href="javascript:cmt.getCaptcha();"><img name="captchax" src="http://www.pcauto.com.cn/blank.gif" id="captchax" alt=""></a>
		                    </div>
		                    <div class="c-btn"  onclick="ajaxComment();"><span class="c-submit" id="cmtSubmit">发表</span></div>
		                </div>
					</c:when>
					<c:otherwise>
						<div class="m-lylist-tips">只有该车友会成员才能发表留言哦~</div>
					</c:otherwise>
				</c:choose>
			</c:if>
            </div>
            <div style="display: none;" class="m-none" id="nodata"><span>  &gt;_&lt; lll</span><p>该车友会还没车友留言哦~</p></div>
            <div id="commentList">

            </div>
        </div>

        <div class="btn-more" id="showMore"><a id="J-more" onclick="loadMore();">点击查看更多</a></div>

        <!--隐藏评论输入框-->
        <div class="comment" id="comment_pop" style="display: none;">
            <!-- 评论输入 -->
            <div class="c-input">
                <div class="c-top">
                    <div class="c-face"><span class="c-face-btn">表情</span><span class="c-face-list"></span></div>
                </div>
                <div class="c-area">
                    <textarea id="content_pop" rows="" cols="" placeholder="在这里输入留言"></textarea>
                </div>
                <div class="c-check" id="cmtCheck_pop">
                    <input type="text" id="captcha_pop" placeholder="验证码"><a href="javascript:cmt.getCaptcha();"><img name="captchax" src="http://www.pcauto.com.cn/blank.gif" id="captchax_pop" alt=""></a>
                </div>
                <div class="c-btn" onclick="ajaxReply(this)"><span class="c-submit" id="cmtSubmit_pop" >发表</span></div>
            </div>
        </div>

        <div id="Jfoot" class="g-footer">
            <!-- 公共底部 -->
            <%@include file="../common/intf5987.html" %>
        </div>
        <script type="text/javascript" src="http://js.3conline.com/wap/2013/common/js/zepto.min.js"></script>

        <script>
            var faceStr = '<img title="[嘻嘻]" src="http://www.pconline.com.cn/images/comment/face201.gif"><img title="[酷]" src="http://www.pconline.com.cn/images/comment/face202.gif"><img title="[汗]" src="http://www.pconline.com.cn/images/comment/face203.gif"><img title="[鄙视]" src="http://www.pconline.com.cn/images/comment/face204.gif"><img title="[阴险]" src="http://www.pconline.com.cn/images/comment/face205.gif"><img title="[强]" src="http://www.pconline.com.cn/images/comment/face206.gif"><img title="[弱]" src="http://www.pconline.com.cn/images/comment/face207.gif"><img title="[花]" src="http://www.pconline.com.cn/images/comment/face208.gif"><img title="[便便]" src="http://www.pconline.com.cn/images/comment/face209.gif"><img title="[亲]" src="http://www.pconline.com.cn/images/comment/face210.gif">';
            var commentHTML= '<div class="m-lywrap" data-meta="{userName}"><div class="m-lyth"><a href="${UCROOT}/my/{userId}">'
                +'<img src="{imgUrl}"/></a><span><a href="${UCWAPROOT}/{userId}">{userName}</a></span></div><div class="m-lytb">'
                +'<div class="m-lybody">{content}' //   <!-- 每张图片间保留换行或者空格 -->
                +'{imgHtml}</div><div id="replyDiv{commentId}">{replyHtml}</div>'
                +'<div class="m-lyctr"><span class="date">{createDate}</span>'
                +'<input type="hidden" name="commentId" value="{commentId}"/>'
                +'<a class="repost" href="javascript:;" style="display:${isMember?"block":"none"}">回复</a></div></div></div>';
            var replyHTML = '<div class="m-lyrepeat">{userName}:{content}</div>';
            function Transfer(url, callback, options) {
                this.url = url;
                this.callback = callback;

                var op = {
                    localProxy : '/favicon.ico',
                    defaultName : 'cross.default.name'
                };
                this.options = this.extend(op, options);

                this.init();
            }

            Transfer.prototype = {
                init : function() {
                    // ============ helper functions
                    function createNamedElement(type, name) {
                        var element = null;
                        // Try the IE way; this fails on standards-compliant browsers
                        try {
                            element = document.createElement('<' + type + ' name="' + name
                                + '">');
                        } catch (e) {
                        }
                        if (!element || element.nodeName != type.toUpperCase()) {
                            // Non-IE browser; use canonical method to create named element
                            element = document.createElement(type);
                            element.name = name;
                        }
                        return element;
                    }
                    // ============

                    // add windowname mark
                    this.params = this.options.params || {};
                    this.params.windowname = 1;
                    delete this.options.params;

                    this.files = this.options.files || [];
                    delete this.options.files;

                    // create form and iframe and add to document
                    var uuid = 'transfer_' + new Date().getTime();

                    var frame = createNamedElement('iframe', uuid);
                    // Give the frame a name to hide it from frames.length
                    frame.name = uuid;
                    // Hide frame. Avoid `display:none` to work with old Safari.
                    frame.style.display = 'none';
                    frame.style.position = 'fixed';
                    frame.style.top = frame.style.left = '-10000px';
                    document.body.appendChild(frame);

                    // use form to post data and put response into iframe
                    var form = document.createElement('form');
                    form.style.display = 'none';
                    // The form posts to the URL
                    form.target = uuid;
                    form.action = this.url;
                    form.method = 'post';
                    form.enctype = 'application/x-www-form-urlencoded';
                    document.body.appendChild(form);

                    this.frame = frame;
                    this.form = form;

                    // state:
                    // 1: init
                    // 2: set to request location
                    // 3: response from request location
                    this.state = 1;

                    this._setRequest();
                },
                _setRequest : function() {
                    var self = this, frame = self.frame, form = self.form, options = self.options, localProxy = options.localProxy, done = false;

                    if (frame.onreadystatechange !== undefined) {
                        frame.onreadystatechange = onrequest;
                    } else {
                        frame.onload = onrequest;
                    }

                    // when success get response by window.name, call callback
                    function complete() {
                        var data = frame.contentWindow.name;
                        // if fail to fetch the name, make it error
                        if (data == options.defaultName)
                            data = '{"error": 1}';
                        eval('var result = ' + data);
                        self.callback(result);
                    }

                    function isLocal() {
                        var c = false;
                        try {
                            c = frame.contentWindow.location.host == location.host;
                            // try to get location - if we can we're still local and have to
                            // wait some more...
                        } catch (er) {
                            // if we're at foreign location we're sure we can proceed
                        }
                        return c;
                    }

                    function clean() {
                        frame.onreadystatechange = frame.onload = null;
                        frame.parentNode.removeChild(frame);
                        if (form) {
                            var fileArr;
                            for ( var i = 0, l = self._files.length; i < l; i++) {
                                fileArr = self._files[i];
                                // put file input back to origin place and remove the
                                // cloneNode
                                fileArr[2].insertBefore(fileArr[0], fileArr[1]);
                                fileArr[2].removeChild(fileArr[1]);
                            }
                            fileArr = null;
                            self._files = [];
                            form.parentNode.removeChild(form);
                        }
                        frame = null;
                        form = null;
                        for ( var j in self) {
                            if (self.hasOwnProperty(j)) {
                                self[j] = null;
                                delete self[j];
                            }
                        }
                    }

                    function onrequest() {
                        try {
                            // opera 的 frame 请求加载机制似有所不同，跳过了 state 为 1 的部分，直接进入 state 为 2
                            // 的情况；
                            // 导致 form 改变 iframe 文档的 location 还没生效，保持为 blank
                            if (frame.contentWindow.location.href == 'about:blank')
                                return;
                        } catch (e) {
                        }

                        if (self.state == 3) {
                            if (!isLocal()) {
                                // need to set back to local location in order to have grant
                                // to access window.name
                                frame.contentWindow.location = localProxy;
                            } else {
                                // ie
                                if (frame.readyState && frame.readyState.toLowerCase() != 'complete')
                                    return;

                                complete();
                                done = true;
                                clean();
                            }
                        }

                        if (self.state == 2) {
                            frame.contentWindow.location = localProxy;
                            self.state = 3;
                        }
                    }
                },
                send : function() {
                    var params = this.params, files = this.files, form = this.form, key, v;

                    var _toString = Object.prototype.toString;

                    // Build form fields from data
                    for (key in params) {
                        if (params.hasOwnProperty(key)) {
                            v = params[key];
                            if (_toString.call(v) === '[object Array]') {
                                var _key = key + '[]';
                                for ( var i = 0, l = v.length; i < l; i++) {
                                    form.appendChild(genInput(_key, v[i]));
                                }
                            } else {
                                form.appendChild(genInput(key, v));
                            }

                        }
                    }

                    // if exist input[type="file"] elements,
                    // because can not copy the file input's value, create a clone,
                    // insert the clone before the file input, and move the origin file
                    // input to the submit form
                    // in order to restore the file inputs,
                    // save the relation with an array [fileEle, clone, parentNode]
                    var fEle, fpEle, fCloneEle;
                    var _files = this._files = [];
                    var fl = files.length;
                    if (fl > 0) {
                        form.encoding = form.enctype = 'multipart/form-data';

                        for ( var fi = 0; fi < fl; fi++) {
                            fEle = files[fi];
                            fpEle = fEle.parentNode;
                            fCloneEle = fEle.cloneNode();
                            //fCloneEle.disabled = 'disabled';
                            _files.push([ fEle, fCloneEle, fpEle ]);
                            fpEle.insertBefore(fCloneEle, fEle);
                            form.appendChild(fEle);
                        }
                    }
                    fEle = fpEle = fCloneEle = null;

                    // alert(form.enctype);

                    form.submit();

                    this.state = 2;

                    if (this.frame.contentWindow) {
                        this.frame.contentWindow.name = this.options.defaultName;
                    }

                    // generate input element with given name and value
                    function genInput(name, value) {
                        var input = document.createElement('input');
                        input.name = name;
                        input.value = value;
                        return input;
                    }
                },
                isObject : function(obj) {
                    return Object.prototype.toString.call(obj) == '[object Object]'
                        && !obj.nodeType;
                },
                isArray : function(obj) {
                    return Object.prototype.toString.call(obj) == '[object Array]';
                },
                extend : function(target, source) {
                    // deep extend
                    var clone = this.clone(source);
                    var i;
                    for (i in clone) {
                        if (clone.hasOwnProperty(i)) {
                            target[i] = clone[i];
                        }
                    }
                    return target;
                },
                clone : function(o) {
                    var self = this, ret;

                    if (self.isArray(o)) {
                        ret = [];
                        for ( var i = 0, l = o.length; i < l; i++) {
                            ret.push(self.clone(o[i]));
                        }
                    } else if (self.isObject(o)) {
                        ret = {};
                        for ( var k in o) {
                            if (o.hasOwnProperty(k)) {
                                ret[k] = self.clone(o[k]);
                            }
                        }
                    } else {
                        ret = o;
                    }

                    return ret;
                }
            };

            var retCodeDict = new Array();
            retCodeDict[0] = "成功";
            retCodeDict[1] = "事务编码未指定";
            retCodeDict[2] = "事务编码不存在";
            retCodeDict[3] = "创建事务失败";
            retCodeDict[4] = "非法的参数";
            retCodeDict[5] = "上传失败";
            retCodeDict[6] = "处理失败";
            retCodeDict[7] = "事务已关闭";
            retCodeDict[8] = "删除事务失败";
            retCodeDict[9] = "资源删除失败";
            retCodeDict[10] = "未指定资源";
            retCodeDict[11] = "资源更新失败";
            retCodeDict[12] = "用户未登录";
            retCodeDict[13] = "非法的状态";
            retCodeDict[14] = "文件大小超出规定";
            retCodeDict[15] = "未指定应用编码";
            retCodeDict[100] = "未知错误";

            retCodeDict[702] = "参数不正确";

            var UPC = {
                upcPath : null,
                application : null,
                windowname : null,
                command : null,
                sessionCookieName : null,
                sessionCookieValue : null,
                retCodeJson : function(c) {
                    eval("var errResult={retCode:" + c + ",desc:'" + this.retCodeResult[c]
                        + "'}");
                    return errResult;
                },
                init : function(s) {
                    this.upcPath = s.upcPath || "";
                    this.application = s.application || null;
                    this.windowname = s.windowname || 1;
                    this.command = s.command || null;
                    
                    this.sessionCookieName = s.sessionCookieName || "common_session_id";
                    this.sessionCookieValue = this.Util.getCookie(this.sessionCookieName);
                },
                overInit : function(n, v) {
                    if (v == "") {
                        return true;
                    }
                    if (n == "application") {
                        this.application = v;
                        return true;
                    } else if (n == "windowname") {
                        this.windowname = v;
                        return true;
                    } else if (n == "command") {
                        this.command = v;
                        return true;
                    } else if (n == "sessionCookieName") {
                        this.sessionCookieName = v;
                        this.sessionCookieValue = this.Util
                        .getCookie(this.sessionCookieName);
                        return true;
                    }
                    return false;
                },
                retCodeResult : function(code) {
                    return retCodeDict[code];
                },
                applicationPara : function() {
                    return this.application == null ? "" : "&application="
                        + this.application;
                },
                commandPara : function() {
                    if (this.command == null)
                        return "";
                    var cm = ""
                    if (typeof (this.command) == "object") {
                        for ( var i = 0; i < this.command.length; i++) {
                            cm += ("&command=" + this.command[i]);
                        }
                    } else {
                        cm = this.command;
                    }
                    return cm;
                },
                sessionCookiePara : function() {
                    return this.sessionCookieName == null ? "" : "&"
                        + this.sessionCookieName + "=" + this.sessionCookieValue;
                },
                windownamePara : function() {
                    return this.windowname == null ? "" : "&windowname=" + this.windowname;
                },
                post : function(s) {
                    var postUrl = s.url || null;
                    var datas = s.data || null;
                    if (postUrl == null || datas == null)
                        return this.retCodeJson(702);
                    var params = this.Util.praseParam(datas);
                    if (params == null)
                        return this.retCodeJson(702);
                    postUrl = this.upcPath + postUrl + "?" + this.applicationPara()
                        + this.windownamePara() + this.commandPara()
                        + this.sessionCookiePara() + params;
                    var callback = null;
                    if (s.complete && typeof (s.complete) == "function") {
                        callback = s.complete;
                    }
                    if (s.before && typeof (s.before) == "function") {
                        s.before();
                    }
                    var fileIds = s.file || null;
                    var bitmapData = s.fileData || null;
                    //UPC.WindownameUtil.send(postUrl, fileId, callback, bitmapData);
                    var files = [];
                    for(var i = 0, l = fileIds.length; i < l; i++) {
                        files.push(document.getElementById(fileIds[i]));
                    }
                    var data = {
                        "files": files
                    };
                    var t = new Transfer(postUrl, callback, data);
                    delete t.params.windowname; // 这里用得是在 url 中传 windowname
                    t.send();
                },
                WindownameUtil : {
                    iframeLoadStep : null,
                    userCallback : null,
                    send : function(url, fileId, callback, bitmapData) {
                        this.iframeLoadStep = 1;
                        this.userCallback = callback;

                        var encType = (fileId != null && (typeof (fileId) == "object" || typeof (fileId) == "string")) ? "encType='multipart/form-data'"
                        : "";
                        var windownameForm = jQuery('<form action="" id="windownameFormId" '
                            + encType
                            + ' name="windownameFormId" method="POST" target="windownameFrame" style="display:none"><span id="windownameSpan"></span></form>');
                        jQuery(windownameForm).appendTo("body");
                        if (fileId != null && typeof (fileId) == "object") {
                            for ( var i = 0; i < fileId.length; i++) {
                                var oldElement = jQuery("#" + fileId[i]);
                                jQuery(oldElement).attr("id", "windownameFile");
                                jQuery(oldElement).appendTo(windownameForm);
                            }
                        }
                        if (bitmapData != null) {
                            jQuery("<input type='hidden' name='fileData'/>")
                            .val(bitmapData).appendTo(windownameForm);
                        }
                        jQuery("#windownameFormId").attr("action", url);
                        jQuery("#windownameSpan")
                        .append(
                        '<iframe name="windownameFrame" id="windownameFrame" style="display:none"></iframe>');
                        jQuery("#windownameFrame").bind("load", function(e) {
                            UPC.WindownameUtil.getData();
                        });
                        jQuery("#windownameFormId").submit();
                    },
                    getData : function() {
                        switch (this.iframeLoadStep) {
                            case 1:
                                this.iframeLoadStep++;
                                document.getElementById("windownameFrame").contentWindow.location.href = '/proxy.txt';
                                break;
                            case 2:
                                var jret = document.getElementById("windownameFrame").contentWindow.name;
                                this.clearup();
                                eval("var result = " + jret);
                                if (this.userCallback
                                    && typeof (this.userCallback) == "function") {
                                    this.userCallback(result);
                                }
                                break;
                        }
                    },
                    clearup : function() {
                        //document.getElementById("windownameFrame").contentWindow.document.write("");
                        document.getElementById("windownameFrame").contentWindow.close();
                        jQuery("#windownameFrame").unbind("load");
                        jQuery("#windownameSpan").empty();
                        jQuery("#windownameFile").remove();
                        jQuery("#windownameFormId").remove();
                    }
                },
                Util : {
                    praseParam : function(s) {
                        if (typeof (s) == "number" || typeof (s) == "boolean"
                            || typeof (s) == "function" || typeof (s) == "undefined")
                            return null;
                        if (typeof (s) == "string" && s.length == 0)
                            return null;
                        if (typeof (s) == "string")
                            return s;
                        if (s && typeof (s) == "object") {
                            var str = "";
                            for (na in s) {
                                var v = s[na];
                                if (UPC.overInit(na, v))
                                    continue;//over init value
                                if (typeof (v) == "object") {
                                    for (cm in v) {
                                        str += ("&" + na + "=" + cm)
                                    }
                                    ;
                                } else {
                                    str += ("&" + na + "=" + v);
                                }
                            }
                            return str;
                        }
                        return null;
                    },
                    getCookie : function(name) {
                        var arr = document.cookie.match(new RegExp("(^| )" + name
                            + "=([^;]*)(;|$)"));
                        if (arr != null)
                            return unescape(arr[2]);
                        return null;
                    }
                }
            }

            //+++++++++++多图上传js+++++++++++
            var imgData = [];//图片数组
            var picNum = 0;//上传图片张数
            var picWrap = document.getElementById('picWrap');//图片外壳
            var picfileWrap = document.getElementById('picfileWrap');//上传控件外壳
            var idNum = 0;//控件id值

            //创建不同name和id值的上传空间
            function createInput() {
                idNum++;
                var inputEle = document.createElement("input");
                inputEle.setAttribute("onchange","changeEvent(this)");
                inputEle.className = 'picfile';
                inputEle.type = 'file';
                inputEle.accept = 'image/*';//只限定图片
                inputEle.id = "picfile"+idNum;
                inputEle.name = "picfile"+idNum;
                picfileWrap.appendChild(inputEle);
            }

            //每次选择完图片上传 , 同时隐藏这个上传控件 , 创建下一个不同id和name值的控件,这样做是为了能够实现多图片同时上传
            function changeEvent(obj) {
                //obj.id = "picfile"+idNum;
                if(!obj){
                    return;
                }
                obj.style.display = "none";
                doUpload(obj.id);
                createInput();
            }

            //删除picitems
            function delItems(obj) {
                if(!obj){
                    return;
                }
                picNum--;
                obj.parentNode.removeChild(obj);
            }
            //
            //console.log(picNum);
            //console.log(imgData);

            function doUpload(fileId) {
                if (picNum >= 2) {
                    showTopTip("只能上传两张图片喔~");
                    hideTopTip();
                    return;
                }
                UPC.init({
                    localProxy : '/favicon.ico',
                    //          upcPath:"http://upctemp.pcauto.com.cn",
                    upcPath:"${cfg.uploadRoot}",
                    command:[53005,53003],
                    application:"autoclub"
                });
                UPC.post({
                    //        url:"/upload_quick.jsp",
                    url:"/upload_quick.jsp",
                    data:{rotate:0,keepSrc:'yes',readExif:'yes',waterMark :"/data/pc-config/upc/watermark/uc_auto.png"},
                    file:[fileId],
                    complete:upcComplete
                });

                //插入loading外壳
                var divEle = document.createElement("div");
                //divEle.setAttribute("onclick","delItems(this)");
                divEle.className = 'items';
                picWrap.appendChild(divEle);
            }

            function upcComplete(json){
                if (json.retCode == 0) {
                    picNum++;
                    picWrap.querySelectorAll(".items")[picNum-1].innerHTML = '<img src="' + json.files[0].url + '" />';//传图成功插入图片
                    imgData.push(doUploadPic(json.files));//把原图push进数组

                    //每次图片传完重新赋予删除事件
                    for (var i = 0 , len=picWrap.querySelectorAll(".items").length; i < len ; i++) {
                        (function (m) {
                            picWrap.querySelectorAll(".items")[m].onclick = function () {
                                picNum--;
                                picWrap.removeChild(this);
                                imgData.splice(m,1);
                            }
                        })(i)
                    }
                    //清空文件域
                    //var obj = document.getElementById("picfile");
                    //obj.outerHTML = obj.outerHTML;
                } else {
                    picNum++;
                    //alert("上传图片失败...retCode>>>" + json.retCode);
                    //console.log("上传图片失败...retCode>>>" + json.retCode);
                    showTopTip("上传图片失败");
                    hideTopTip();
                    picWrap.removeChild(picWrap.querySelectorAll(".items")[picNum-1]);
                    picNum--;
                }
            }

            function appendImg(imgData){
                var str = '\r\n';
                for(var i =0;i<imgData.length;i++){
                    str += '[img]';
                    str += imgData[i];
                    str += '[/img]\r\n';
                }
                return str;
            }

            //提示信息
            function showTopTip(msg) {
                var tipEle = document.getElementById('topTipMsg');
                var w0 = document.body.clientWidth;
                var w = Math.min(w0, 600);
                var left = (w0 - w) / 2;  
                var h = '22px';
    
                if(!tipEle) {
                    tipEle = document.createElement('div');
                    tipEle.id = 'topTipMsg';
                    tipEle.style.cssText = 'position:fixed; top:-' + h + '; width:' + w + 'px; height:22px; line-height:22px; font-size:14px; background:rgba(48,48,48,0.7); color:#ccc; line-height:1.5; text-align:center; -webkit-transition:top 0.3s ease-in; -webkit-border-radius:0 0 5px 5px;-moz-border-radius:0 0 5px 5px;border-radius:0 0 5px 5px;z-index:10';
                    document.body.appendChild(tipEle);
                }
    
                tipEle.innerHTML = msg;
    
                tipEle.style.display = 'block';
                tipEle.style.left = left + 'px';
    
                // timeout to make transition avaliable
                setTimeout(function(){
                    tipEle.style.top = '0';
                }, 0);
            }
            //隐藏提示信息
            function hideTopTip() {
                var tipEle = document.getElementById('topTipMsg');
                if(tipEle) {
                    setTimeout(function(){
                        tipEle.style.top = '-22px';
                        setTimeout(function(){
                            tipEle.style.display = 'none';
                        }, 300);
                    },2500);
                }
            }

            /*留言*/
            (function(){
                var lastReplyCmtWrap;
                // 切换显示表情
                function toggleFace(faceBtn) {
                    var cmt = closest(faceBtn, '.comment');
                    if(cmt) {
                        cmt.className = cmt.className == 'comment face-open' ? 'comment' : 'comment face-open';
                    }
                }
                // 移动/切换显示回复框
                function showPopForm(btn) {
                    var wrap = closest(btn, '.m-lywrap');
                    if(!wrap) return;
        
                    var cmt = document.getElementById('comment_pop');
                    var metaData = wrap.getAttribute('data-meta'); 
        
                    if(cmt.parentNode == wrap) {
                        // if already here, just toggle it
                        if(btn.innerHTML == '回复') {
                            btn.innerHTML = '收起';
                            cmt.style.display = 'block';
                            document.getElementById('content_pop').placeholder = "回复"+ metaData +"：";
                        } else {
                            btn.innerHTML = '回复';
                            cmt.style.display = 'none';
                        }                
                    } else {
                        // 转移评论框后把上一次的评论按钮字样调整
                        if(lastReplyCmtWrap) {
                            lastReplyCmtWrap.querySelector('.repost').innerHTML = '回复';
                        }
            
                        btn.innerHTML = '收起';
            
                        // move comment_pop here
                        lastReplyCmtWrap = wrap;
                        wrap.appendChild(cmt);
                        cmt.style.display = 'block';
            
                        // placeholder            
                        document.getElementById('content_pop').placeholder = "回复"+ metaData +"：";
                    }
                }
                // selector 只能用简单的选择器，#id, tagName, .className，单个无组合
                function closest(ele, selector) {
                    var result,
                    tmp = ele.parentNode;

                    while (tmp) {
                        if (matchSelector(tmp, selector)) {
                            result = tmp;
                            break;
                        }
                        tmp = tmp.parentNode;
                    }
                    return result;
                }
                function matchSelector(ele, selector) {
                    // if use id
                    if (selector.charAt(0) === '#') {
                        return ele.id === selector.slice(1);
                    }
                    // if use class
                    if (selector.charAt(0) === '.') {
                        return (' ' + ele.className + ' ').indexOf(' ' + selector.slice(1) + ' ') != -1;
                    }
                    // if use tagName
                    return ele.tagName.toLowerCase() === selector.toLowerCase();
                }
                // ============ 简单的事件委托
                function delegateEvent(interfaceEle, selector, type, fn) {
                    interfaceEle.addEventListener(type, function(e) {
                        if (matchSelector(e.target, selector)) {
                            if(fn) {
                                fn.call(e.target, e);
                            }
                        }
                    });
                }
                // 事件绑定
                var mainEle = document.getElementById('J-main');
                // 触发切换显示表情
                var faceBtns = document.querySelectorAll('.comment .c-face-btn');
                for(var i=faceBtns.length - 1; i >= 0; i--) {
                    (function(n){
                        var item = faceBtns[n];
                        item.addEventListener('click', function(e){
                            var parentNode = item.parentNode,
                            listObj = parentNode.querySelector(".c-face-list");
                            if(listObj.children.length==0){
                                listObj.innerHTML = faceStr;
                            }
                            toggleFace(item, '.comment');
                        });
                    })(i);          
                }

                // 点击表情, append title(ubb code)
                var faceList = Array.prototype.slice.call(document.querySelectorAll('.comment .c-face-list'));
                faceList.forEach(function(item){
                    var imgs = item.getElementsByTagName('img');
                    
                    delegateEvent(item, 'img', 'click', function(){
                        // show clicking which face
                        var that = this;
                        that.className = 'hlight';
                        setTimeout(function(){
                            that.className = '';
                        }, 300);
            
                        var cmt = closest(this, '.comment');
                        if(cmt) {
                            var textarea = cmt.querySelector('textarea');
                            if(textarea) {
                                textarea.value += this.title;
                            }
                        }
                    });
                });

                // 点击回复评论按钮        
                delegateEvent(mainEle, '.repost', 'click', function(e){
                    showPopForm(this);
                });

            })()
            function isLogin(){
                if(${empty user || user.uid==0}){
                    return false;
                }
                return true;
            }
            function isMember(){
                if(${isMember}){
                    return true;
                }
                return false;
            }
            function clearPhoto(){
                picNum = 0;
                imgData = [];
                $("#picWrap").html("");
            }
            var baseUrl = "${WAPROOT}";
            var pageNo = 1;
            var pageSize = 5;
            var clubId = "${club.clubId}";
            var reg=new RegExp("\\[em(\\d{3})\\]","ig");
            var r = new RegExp("\\{(\\d{3})\\}","ig");
            //表情转换
            function showMod(html){
                var result = html.replace(reg, '<img src="http://www.pconline.com.cn/images/comment/face$1.gif">');
                result = result.replace(r, '<img src="http://www.pconline.com.cn/images/comment/face$1.gif">');
                return result;
            }
            // 发送留言前转换表情代码
            function translateFace(str) {
                var code = ['{201}', '{202}', '{203}', '{204}', '{205}', '{206}', '{207}', '{208}', '{209}', '{210}'];
                var name = ['[嘻嘻]', '[酷]', '[汗]', '[鄙视]', '[阴险]', '[强]', '[弱]', '[花]', '[便便]', '[亲]'];
                var p;
        
                for(var i=code.length-1; i>=0; i--) {
                    p = new RegExp(name[i].replace('[', '\\[').replace(']', '\\]'), 'gm');
                    str = str.replace(p, code[i]);
                }
                return str;
            }
            function getComment(spageNo){
                $.getJSON("${ROOT}/comment/loadCommentByAjax.do?req_enc=utf-8&resp_enc=utf-8&callback=?&_t="+new Date().getTime(), {pageNo:spageNo,clubId:clubId,pageSize:pageSize}, function(data){
                    if(data.result){
                        var d  = data.result;
                        addComment(d,true);
                        pageNo = data.pageNo;
                        if(pageNo >= data.totalCount){
                            $("#showMore").hide();
                        }
                        if(data.total==0){
                            $("#nodata").show();
                        }
                    }
                });
               
            }
            function addComment(d,type){
                var html = "";
                for(var i = 0;i<d.length;i++){
                    var replyHtml = "";
                    var imgHtml = "";
                    if(d[i].imgUrl1!="" && d[i].imgUrl1!=null){
                        if(d[i].imgUrl1[0]!=""){
                            imgHtml+='<img width="240" height="80" src="{imgUrl1}"> '.replace(/{imgUrl1}/ig, d[i].imgUrl1[0]);
                        }
                    }
                    if(d[i].imgUrl2!="" && d[i].imgUrl2!=null){
                        if(d[i].imgUrl2[0]!=""){
                            if(imgHtml!="" && imgHtml.length>0){
                                imgHtml+="&nbsp;";
                            }
                            imgHtml+=' <img width="240" height="80" src="{imgUrl2}">'.replace(/{imgUrl2}/ig, d[i].imgUrl2[0]);
                        }
                               
                    }
                            
                    if(d[i].replys.length>0){
                        var r = d[i].replys;
                        for(var j =0;j<r.length;j++){
                            var replyContent = showMod(r[j].content);
                            replyHtml +=replyHTML.replace(/{userName}/ig, r[j].userName).replace(/{content}/ig,replyContent);
                        }
                                
                    }
                    if(d[i].content!=""){
                        imgHtml="<br/>"+imgHtml;
                    }
                    var content = showMod(d[i].content);
                    html+=commentHTML.replace(/{userName}/ig,d[i].userName).replace(/{content}/ig,content).replace(/{imgUrl}/ig,d[i].imgUrl).replace(/{imgHtml}/ig,imgHtml).replace(/{replyHtml}/ig,replyHtml).replace(/{commentId}/ig,d[i].commentId).replace(/{createDate}/ig,d[i].createDate).replace(/{userId}/ig,d[i].createBy);
                            
                }
                if (type) {
                    $("#commentList").append(html);
                } else {
                    $("#commentList").prepend(html);
                }
                // 隐藏空文案
                $('#nodata').css('display') != 'none' ? $('#nodata').css('display', 'none') : '';
            }
            function addReply(d){
                var html = "";
                var content = showMod(d.content);
                html+=replyHTML.replace(/{userName}/ig,d.userName).replace(/{content}/ig,content);
                $("#replyDiv"+d.replyId).append(html);
            }
            function checkInfo(content){
                if(content.val()=="" && imgData.length==0){
                    showTopTip("发表内容不能为空！");
                    hideTopTip();
                    return false
                }
                return true;
            }
            function ajaxComment(){
                if(!isLogin()){
                    showTopTip("请先登录后再发言！");
                    hideTopTip();
                    return;
                }
                if(!isMember()){
                    showTopTip("不是该车友会会员不能发言！");
                    hideTopTip();
                    return;
                }
                if(!checkInfo($("#content"))){
                    return;
                }
                showTopTip("发表中...");
                var imgUrl1="";
                var imgUrl2="";
                if(imgData.length>0){
                    imgUrl1=imgData[0];
                    if(imgData.length>1){
                        imgUrl2 = imgData[1];
                    }
                }
                var params = {
                    content:translateFace($("#content").val()),
                    clubId:clubId,
                    imgUrl1:imgUrl1,
                    imgUrl2:imgUrl2,
                    replyId:0
                };
                $.post(baseUrl+"/comment/addComment.do?req_enc=utf-8&resp_enc=utf-8",params,commentCallback);
            }
            function doUploadPic(imgData){
            	var url = "";
            	for(var i=0;i<imgData.length;i++){
            		if(imgData[i].url.indexOf("_240")>0){
            			url = imgData[i].url;
            		}
            	}
            	return url;
            }
            function ajaxReply(e){
                if(!isLogin()){
                    showTopTip("请先登录后再回复！");
                    hideTopTip();
                    return;
                }
                if(!isMember()){
                    showTopTip("不是该车友会会员不能回复！");
                    hideTopTip();
                    return;
                }
                if(!checkInfo($("#content_pop"))){
                    return;
                }
                showTopTip("回复中...");
                var replyId  = $(e).parents(".m-lywrap").find("[name=commentId]").val();
                var content = $("#content_pop").val();
                if(content.length<=0 || content==""){
                    showTopTip("内容不能为空！");
                    hideTopTip();
                    return;
                }
                var params={
                    replyId:replyId,
                    content:translateFace(content),
                    imgUrl1:"",
                    imgUrl2:"",
                    clubId : clubId
                };
                $.post(baseUrl+"/comment/addComment.do?req_enc=utf-8&resp_enc=utf-8", params, replyCallback);
            }
            
            function commentCallback(data){
                data = eval("("+data+")");
                if(data.code==0){
                    addComment(data.result,false);
                    showTopTip(data.message);
                    $("#content").val("");
                    clearPhoto();
                    hideTopTip();
                }else{
                    showTopTip(data.message);
                    hideTopTip();
                }
            }
            function replyCallback(data){
                data = eval("("+data+")");
                if(data.code==0){
                    if(data.result.length>0){
                        addReply(data.result[0]);
                        showTopTip(data.message);
                        $("#content_pop").val("");
                        hideTopTip();
                    }
                }else{
                    showTopTip(data.message);
                    hideTopTip();
                }
            }
            function loadMore(){
                getComment(pageNo+1);
            }
            $(document).ready(function(){
                getComment(1);
            });
        </script>
    </body>
</html>